class_name Enemy
extends CharacterBody2D

var room: Room
@export var speed: float = 50.0

var attack_ready = true

signal on_die(enemy: Enemy)

func die() -> void:
	queue_free()
	on_die.emit(self)

func set_room(_room: Room) -> void:
	room = _room

func _physics_process(_delta: float) -> void:
	if room != null:
		if room.soldiers.size() > 0:
			goto_solider()
			attack_solider()
		elif room.player:
			goto_player()
			attack_player()

func goto_solider() -> void:
	if room.soldiers.size() > 0:
		var nearest_solider := room.soldiers[0]
		for i in range(1, room.soldiers.size()):
			var solider := room.soldiers[i]
			if (solider.global_position - global_position).length() < (nearest_solider.global_position - global_position).length():
				nearest_solider = solider
		look_at(nearest_solider.global_position)
		velocity = (nearest_solider.global_position - global_position).normalized() * speed
		move_and_slide()

func goto_player() -> void:
	if room.player != null:
		look_at(room.player.global_position)
		velocity = (room.player.global_position - global_position).normalized() * speed
		move_and_slide()

func attack_solider() -> void:
	if room.soldiers.size() > 0 and attack_ready:
		var nearest_solider := room.soldiers[0]
		for i in range(1, room.soldiers.size()):
			var solider := room.soldiers[i]
			if (solider.global_position - global_position).length() < (nearest_solider.global_position - global_position).length():
				nearest_solider = solider
		if (nearest_solider.global_position - self.global_position).length() <30:
			attack_ready = false
			$Timer.start(1)
			nearest_solider.hurt()
		
		# attack nearest solider

func attack_player() -> void:
	if room.player != null and attack_ready:
		if (room.player.global_position - self.global_position).length() < 50:
			attack_ready = false
			$Timer.start(1)
			room.player.hurt()
		pass


func _on_timer_timeout() -> void:
	attack_ready = true
